var intro = new Intro($('#canvas-intro')[0]);
var ugc = new DIY($('#canvas-ugc')[0]);
var hammer = new HammerEvent("#canvas-ugc");
var movePostion = {x: -50, y: 0};
var hurl = "http://pandora-2018xmas.shjiaoai.com/";//测试

document.getElementById("wrap").addEventListener('touchmove' , function (ev){
	ev.preventDefault();
	return false;
} , {passive: false});


var bgID = 1;//背景id, 1-9

var swiper_bg;
var step = 1;
var currStep = 1;
var status="black",qrcodeimage=3;
var tips = false;
var btnstatus = true,okstatus = true;
function initMain(){
	$('.loading').fadeOut();

	//立即开始
	$('.intro .btn-start').click(function(){
		intro.onStop();
		$('.intro').fadeOut();
		$(".shake-icon").addClass("swinging");
		onShake();
		ggTrack('立即开始');
	});
	
	//跳过
	$('.btn_skip').click(function(){
		onSkip();
	});
	var bgUrl = $('.select-bg .swiper-wrapper .swiper-slide').eq(0).find('img').attr('src');
	ugc.setbackground(bgUrl);
	//背景选择器
	swiper_bg = new Swiper('.select-bg .swiper-container', {
		loop:true,
		pagination: {
			el: '.swiper-pagination',
		},
		effect : 'fade',
		on: {
			slideChangeTransitionStart: function(){
				bgID = this.activeIndex + 1;
				status = $('.select-bg .swiper-wrapper .swiper-slide').eq(bgID - 1).find('img').attr('status');
				qrcodeimage = $('.select-bg .swiper-wrapper .swiper-slide').eq(bgID - 1).find('img').attr('qrcode');
				var shake_icon_img = $('.select-bg .shake-tips .shake-icon').attr(status);
				var shake_icon_tips_img = $('.select-bg .shake-tips .shake-icon-tips').attr(status);
				var btn_selcet_comfim = $('.select-bg .btn-selcet-comfim').attr(status);
				var logo_img = $('.select-bg .bgLogo').attr(status);
				$('.select-bg .shake-tips .shake-icon').attr('src', shake_icon_img);
				$('.select-bg .shake-tips .shake-icon-tips').attr('src', shake_icon_tips_img);
				$('.select-bg .btn-selcet-comfim').attr('src', btn_selcet_comfim);
				$('.select-bg .bgLogo').attr('src', logo_img);
				ugc.setLogo(status);

				var save_tips = $('.result .save-tips').attr(status);
				var btn_chakan = $('.result .btn-chakan').attr(status);
				var btn_replay = $('.result .btn-replay').attr(status);
				$('.result .save-tips').attr('src', save_tips);
				$('.result .btn-chakan').attr('src', btn_chakan);
				$('.result .btn-replay').attr('src', btn_replay);
				$('.result .btn-home-black').attr('src', $('.result .btn-home-black').attr(status));
				//console.log(btn_chakan+" : " + btn_replay)
				$(".btn-back").attr('src', $('.btn-back').attr(status));
				$(".btn-ok").attr('srisitc', $('.btn-ok').attr(status));
				var bgUrl = $('.select-bg .swiper-wrapper .swiper-slide').eq(bgID - 1).find('img').attr('src');
				ugc.setbackground(bgUrl);
			},
		},
	});
	swiper_bg.allowTouchMove= false;


	//就是它了
	$('.select-bg .isit').click(function(){
		$('.select-bg').fadeOut();
		if(!tips){
			tips = true;

			var tipstatus = localStorage.getItem("tipstatus");
			if(tipstatus){
				$(".select_tips").hide();
			}
			else{
				$(".select_tips").fadeIn();
			}

		}
		shake = true;
		$('.ugc').fadeIn();
		ggTrack('就是它了');
	});
	
	//返回背景选择
	$(".btn-back").click(function(){
		if(!btnstatus) return false;
		btnstatus = false;
		setTimeout(function(){
			btnstatus = true;
		},2000)
		if(step==1){
			shake = false;
			$('.select-bg').fadeIn();
			ugc.removeAllIcon();
		}else{
			$(".select-icons").show();
			$(".text_con").hide();
			step--;
			currStep = step;
		}
	})
	//提示
	$(".btn_tips_step1").click(function(){
		$(".tips_step1,.tips_step3").fadeOut();
		$(".tips_step2").fadeIn();
	})
	
	$(".btn_tips_step2").click(function(){
		$(".tips_step2,.tips_step1").fadeOut();
		$(".tips_step3").fadeIn();
		
	})
	
	$(".btn_tips_step3").click(function(){
		localStorage.setItem("tipstatus",true);
		$(".select_tips").fadeOut();
	})

	//人物选择
	var swiper_person = new Swiper('#person .swiper-container', {
		slidesPerView: 3,
		slidesPerGroup: 3,
		navigation: {
			nextEl: '#person .swiper-button-next',
			prevEl: '#person .swiper-button-prev',
		},
	});
	
	//礼物选择
	var swiper_gift = new Swiper('#gift .swiper-container', {
		slidesPerView: 3,
		slidesPerGroup: 3,
		navigation: {
			nextEl: '#gift .swiper-button-next',
			prevEl: '#gift .swiper-button-prev',
		},
	});
	
	//气泡选择
	var swiper_say = new Swiper('#say .swiper-container', {
		slidesPerView: 3,
		slidesPerGroup: 3,
		navigation: {
			nextEl: '#say .swiper-button-next',
			prevEl: '#say .swiper-button-prev',
		},
	});
	
	//文字选择
	var swiper_text = new Swiper('#text .swiper-container', {
		slidesPerView: 3,
		slidesPerGroup: 3,
		navigation: {
			nextEl: '#text .swiper-button-next',
			prevEl: '#text .swiper-button-prev',
		},
	});
	
	
	//点击3个label 切换
	$('.ugc .select-icons .labels li').click(function(){
		$('.ugc .select-icons .labels li').css({'background':'#fff'});
		$(this).css({'background':'#f4eff1'});
		var index = $(this).index();
		$(".select_con li:eq("+index+")").css({"opacity":1}).show().siblings().hide();
	});
	
	//点击人物
	$("#person .swiper-slide").click(function(){
		var imgsrc = $(this).find("img").attr(status);
		//imgsrc = imgsrc.replace('png','svg');
		var img = new Image();
		img.src = imgsrc;
		img.onload = function(){
			ugc.addIcon(imgsrc, step, 'people');
		}
	})
	
	//点击礼物
	$("#gift .swiper-slide").click(function(){
		var imgsrc = $(this).find("img").attr(status);
		//imgsrc = imgsrc.replace('png','svg');
		var img = new Image();
		img.src = imgsrc;
		img.onload = function(){
			ugc.addIcon(imgsrc, step, 'gift');
		}
	})
	
	//点击气泡
	$("#say .swiper-slide").click(function(){
		var imgsrc = $(this).find("img").attr("bigImg");
		//imgsrc = imgsrc.replace('png','svg');
		var img = new Image();
		img.src = imgsrc;
		img.onload = function(){
			ugc.addIcon(imgsrc, step, 'pop');
		}
	})
	
	//点击选择文字
	$("#text .swiper-slide").click(function(){
		console.log(status)
		var imgsrc = $(this).find("img").attr(status);
		//imgsrc = imgsrc.replace('png','svg');
		var img = new Image();
		img.src = imgsrc;
		img.onload = function(){
			ugc.addIcon(imgsrc, step, 'text');
		}
	})

	var clickDelay = false;
	//完成作品
	$('.ugc .btn-ok').click(function(){
		if(!okstatus) return false;
		okstatus = false;
		setTimeout(function(){
			okstatus = true;
		},2000)
		if(clickDelay == true) return;
		clickDelay = true;
		ugc.clean();
		setTimeout(function(){ clickDelay = false; }, 2000);

		if(step==1){
			$(".select-icons").hide();
			$(".text_con").show().css({"z-index":100});
			step++;
			currStep = step;
		}else{
			setTimeout(function(){
				step = 1;
				var canvas = document.getElementById("canvas-ugc");
				var base64 = canvas.toDataURL("image/png", 1.0);
				$('.result .temp').attr('src', base64);
				$('.result').delay(200).fadeIn();
				uploadPic(base64);
				
				var ctx = canvas.getContext("2d");
				//底部信息及二维码
				var qrcodeImg = new Image();
				qrcodeImg.src = "img/qr-"+qrcodeimage+".png";
				var tipsImg = new Image();
				if(status=="black"){
					tipsImg.src = "img/save-tips-black.png";
				}else{
					tipsImg.src = "img/save-tips-white.png";
				}
				qrcodeImg.onload = function(){
					//ctx.drawImage(tipsImg,290,1050);
					ctx.drawImage(qrcodeImg,293,1190,164,203);
					var base64 = canvas.toDataURL("image/png", 1.0);
					$('.result .temp_save').attr('src', base64);
				
					$(".select-icons").delay(3000).show();
					$(".text_con").delay(100).hide();
				}
			}, 100);
		}
		
	});
	
	
	//重新打造
	$('.btn-replay').click(function(){
		shake = false;
		$('.result').fadeOut();
		$('.select-bg').fadeIn();
		ugc.removeAllIcon();
		ggTrack('重新打造');
	});
	
	//背景切换测试
	$("#background").click(function(){
		//getBackground();
	})
	
	//查看产品
	$(".btn-chakan").click(function(){
		$(".products").show().css({"opacity":1,"z-index":"100"});
		$(".btn-home-black").show();
		$(".btn-chakan,.btn-replay,.save-tips").hide();
		var myScroll = new IScroll('.product_con', { mouseWheel: true ,scrollbars: true,});
		ggTrack('查看产品');
	})
	
	//关闭产品查看
	$(".products .btn-close").click(function(){
		$(".products,.btn-home-black").hide();
		$(".btn-chakan,.btn-replay,.save-tips").show();
	});

	//产品链接
	$('.product_con a').click(function(){
		var alt = $(this).find('img').attr('alt');
		ggTrack(alt);
	});

	//带我回家
	$('.btn-home-black').click(function(){
		ggTrack('带我回家');
	});
	

}

//跳过
function onSkip(){
	intro.onStop();
	$('.intro').fadeOut();

	onShake();
}

//google监测
function ggTrack(gevent){
	gtag('event', gevent);
}

//摇一摇

var shake = false;
function onShake(){
	if (window.DeviceMotionEvent) {
    	window.addEventListener('devicemotion',deviceMotionHandler,false);
	}
	//获取加速度信息
	//通过监听上一步获取到的x, y, z 值在一定时间范围内的变化率，进行设备是否有进行晃动的判断。
	//而为了防止正常移动的误判，需要给该变化率设置一个合适的临界值。
	var SHAKE_THRESHOLD = 4000;
	var last_update = 0;
	var x, y, z, last_x = 0, last_y = 0, last_z = 0;
	function deviceMotionHandler(eventData) {
	        var acceleration =eventData.accelerationIncludingGravity;
	        var curTime = new Date().getTime();
	        if ((curTime-last_update)> 10) {
	            var diffTime = curTime -last_update;
	            last_update = curTime;
	            x = acceleration.x;
	            y = acceleration.y;
	            z = acceleration.z;
	            var speed = Math.abs(x +y + z - last_x - last_y - last_z) / diffTime * 10000;
	            if (speed > SHAKE_THRESHOLD) {
	            	if(shake==false){
	            		shake = true;
	                	if(swiper_bg != null){
	                		var random = Math.floor(Math.random() * swiper_bg.slides.length);
	                		swiper_bg.slideTo(random)
	                		//swiper_bg.slideNext(0);//背景切换
	                	}
	                	setTimeout(function(){ shake = false; }, 800);
	                }
	            }
	            last_x = x;
	            last_y = y;
	            last_z = z;
	        }
	}
}


//保存图片
function uploadPic(pic) {
    $.ajax({
        type: "Post",
        url: hurl+"/interface/api.aspx?r=" + Math.random(),
        data: {
            "type": "upload_pic",
            "pic": pic,
            "bgID": bgID,
        },
        dataType: "json",
        async: false,
        beforeSend: function (XMLHttpRequest) { },
        success: function (data, textStatus) {
        	//data.picurl, 图片绝对地址
        	//data.id, 图片编号
        	console.log(JSON.stringify(data));
            if (data.errcode == 1) {
                //图片保存成功
                resetShare(data.id);
            } else {
                console.log('图片保存失败:' + data.errmsg);
            }
        }
    });
}


